package ar.com.ford.it.fullEconomics.view.action;

import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.AgreementFacade;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CurrencyFacade;
import ar.com.ford.it.fullEconomics.facade.FullEconomicsFacade;
import ar.com.ford.it.fullEconomics.facade.SupplyFacade;
import ar.com.ford.it.fullEconomics.facade.VehiclelinFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc02Coststvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.AgreementDetailForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class AgreementDetailAction extends AbstractBaseAction {

    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementDetailForm form = (AgreementDetailForm) actionForm;
        form.resetForm();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementFacade agreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        CurrencyFacade currencyFacade = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        VehiclelinFacade lineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);
        form.setAgreement((Teesr03Agreement) request
                .getAttribute("agreementSelected"));

        try {
            request.getSession().setAttribute(
                    "commColl",
                    commodityFacade.findCommodities("", "", user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("partClassColl",
                    commodityFacade.getPartClases());
            request.getSession().setAttribute("currColl",
                    currencyFacade.getAllCurrency());
            request.getSession().setAttribute("lineColl",
                    lineFacade.findAllVehiclelin());
            form.setItems(agreementFacade.findAgreementItems(form
                    .getAgreement()));
            form.setComments(form.getAgreement().getEesr03AgreeCommentsX());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * crea o actualiza un item
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdateAgreementItem(
                                                   FordActionMapping mapping,
                                                   ActionForm actionForm,
                                                   HttpServletRequest request,
                                                   HttpServletResponse response,
                                                   WebSession webSession,
                                                   ActionMessages msgs,
                                                   ActionMessages warns,
                                                   ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementDetailForm form = (AgreementDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementFacade agreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);
        CommodityFacade commodityfacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        SupplyFacade supplyFacade = (SupplyFacade) FacadeProvider.getFacade(
                request, SupplyFacade.class);
        VehiclelinFacade lineFacade = (VehiclelinFacade) FacadeProvider
                .getFacade(request, VehiclelinFacade.class);
        CurrencyFacade currencyFacade = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        FullEconomicsFacade fullEconomicFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);

        Teesr04Agreemitem agreemItem = null;
        try {
            if (form.getEditBlocked().equalsIgnoreCase("false")) {// es create
                agreemItem = new Teesr04Agreemitem();
                agreemItem.setTeesr03Agreement(form.getAgreement());
                if (form.getAgreementScope().equalsIgnoreCase("part")) {
                    Teesp01Part part = new Teesp01Part();
                    part.setEesp01PartClassCodeC(form.getPartClass());
                    part.setEesp01PartPrefixCodeC(form.getPrefix());
                    part.setEesp01PartBaseCodeC(form.getBase());
                    part.setEesp01PartSuffixCodeC(form.getSuffix());
                    Teesp04Supply supply = new Teesp04Supply();
                    supply.setTeesp01Part(part);
                    supply.setTeess01Supplier(agreemItem.getTeesr03Agreement()
                            .getTeess01Supplier());
                    supply.setEesp04PlantCodeC(user.getTeesg01Plant());
                    supply = supplyFacade.getSupplyByPk(supply);
                    if (supply == null) {
                        throw new FullEconomicsException(new Exception(),
                                "requestItem.error.invalidSupply");
                    }
                    agreemItem.setTeesp04Supply(supply);
                    agreemItem.setEesr04AgritmTypeCodeC("P");
                } else if (form.getAgreementScope().equalsIgnoreCase(
                        "commodity")) {
                    Teesp02Commodity commodity = commodityfacade
                            .findCommodityByCode(form.getCommodity(), user
                                    .getTeesg01Plant());
                    agreemItem.setTeesp02Commodity(commodity);
                    agreemItem.setEesr04AgritmTypeCodeC("C");
                } else {
                    agreemItem.setEesr04AgritmTypeCodeC("A");
                }
                if (form.getAgreementClass().equalsIgnoreCase("I")) {
                    agreemItem.setEesr04AgritmIncrPercentP(new BigDecimal(form
                            .getPercentIncrease()));
                } else {
                    agreemItem.setEesr04CurrencyCodeC(currencyFacade
                            .findCurrencyByCode(form.getCurrencyCode()));
                    agreemItem.setEesr04AgritmNewpriceAmounA(new BigDecimal(
                            form.getNewPrice()));
                }
                if (!form.getVehicleLine().equalsIgnoreCase("-1")) {
                	Ncas012VehicleVw line = new Ncas012VehicleVw();
                    line.setCas012VehicleCodeC(form.getVehicleLine());
                    agreemItem.setNcas012VehicleVw(lineFacade
                            .findVehicleLineByPk(line));
                }
                if (!StringUtils.isBlank(form.getFulleeCode())) {
                    agreemItem.setTeesf01Fulleconom(fullEconomicFacade
                            .getFullEconomicsByCode(new Integer(form
                                    .getFulleeCode()), user.getTeesg01Plant()));
                } else {
                    agreemItem.setTeesf01Fulleconom(null);
                }
                agreemItem.setEesr04AgritmEffectiveDateY(new Timestamp(
                        FullEconomicsDateUtil.format(form.getEffectiveDate())
                                .getTimeInMillis()));
                agreementFacade.createAgreementItem(agreemItem, user);
            } else {// es update
                agreemItem = form.getAgreemItemSelected();
                if (!form.getVehicleLine().equalsIgnoreCase("-1")) {
                	Ncas012VehicleVw line = new Ncas012VehicleVw();
                    line.setCas012VehicleCodeC(form.getVehicleLine());
                    agreemItem.setNcas012VehicleVw(lineFacade
                            .findVehicleLineByPk(line));
                } else {
                    agreemItem.setNcas012VehicleVw(null);
                }
                if (form.getAgreementClass().equals("I")) {
                    agreemItem.setEesr04AgritmIncrPercentP(new BigDecimal(form
                            .getPercentIncrease()));
                } else {
                    agreemItem.setEesr04CurrencyCodeC(currencyFacade
                            .findCurrencyByCode(form.getCurrencyCode()));
                    agreemItem.setEesr04AgritmNewpriceAmounA(new BigDecimal(
                            form.getNewPrice()));
                }
                if (!StringUtils.isBlank(form.getFulleeCode())) {
                    agreemItem// XXX implementar getFullEeByCode
                            .setTeesf01Fulleconom(fullEconomicFacade
                                    .findFullEconomicsByCostStrVersion(new Teesc02Coststvers()));
                } else {
                    agreemItem.setTeesf01Fulleconom(null);
                }
                agreemItem.setEesr04AgritmEffectiveDateY(new Timestamp(
                        FullEconomicsDateUtil.format(form.getEffectiveDate())
                                .getTimeInMillis()));
                agreementFacade.updateAgreementItem(agreemItem, user);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        request.setAttribute("agreementSelected", agreemItem
                .getTeesr03Agreement());
        return mapping.findForward("success");
    }

    /**
     * setea el item para ser editado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editAgreementItem(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        AgreementDetailForm form = (AgreementDetailForm) actionForm;

        form.setAgreemItemSelected(form.getAgreemItemByIndex(form
                .getSelectedIndex()));
        form.setItemForEdit(form.getAgreemItemByIndex(form.getSelectedIndex()));
        return mapping.findForward("success");
    }

    /**
     * setea el item para ser editado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward cleanCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {

        AgreementDetailForm form = (AgreementDetailForm) actionForm;

        form.cleanCreateFields();
        return mapping.findForward("success");
    }

    /**
     * borra el item seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteAgreementItem(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementDetailForm form = (AgreementDetailForm) actionForm;
        AgreementFacade facade = (AgreementFacade) FacadeProvider.getFacade(
                request, AgreementFacade.class);
        form.setAgreemItemSelected(form.getAgreemItemByIndex(form
                .getSelectedIndex()));
        try {
            facade.deleteAgreementItem(form.getAgreemItemSelected());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        request.setAttribute("agreementSelected", form.getAgreement());
        return mapping.findForward("success");
    }

    /**
     * setea el item para ser editado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward saveComments(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        AgreementDetailForm form = (AgreementDetailForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        AgreementFacade agreementFacade = (AgreementFacade) FacadeProvider
                .getFacade(request, AgreementFacade.class);

        try {
            form.getAgreement().setEesr03AgreeCommentsX(form.getComments());
            agreementFacade.updateAgreement(form.getAgreement(), user);

        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        request.setAttribute("agreementSelected", form.getAgreement());
        return mapping.findForward("success");
    }
}
